package org.chen.exception;

import org.chen.enu.ErrorType;

/**
 * 统一的错误处理上下文
 */
public class ErrorContext {
    public ErrorType type;
    public String message;
    public boolean retryable;
    public Integer httpStatus;

    public ErrorContext(ErrorType type, String message, boolean retryable, Integer httpStatus) {
        this.type = type;
        this.message = message;
        this.retryable = retryable;
        this.httpStatus = httpStatus;
    }

    // 致命错误工厂方法
    public static ErrorContext fatalError(String message) {
        return new ErrorContext(ErrorType.FATAL_ERROR, message, false, null);
    }

    // HTTP错误工厂方法
    public static ErrorContext httpError(int statusCode, String url) {
        return new ErrorContext(ErrorType.HTTP_ERROR,
                translateHttpErrorMessage(statusCode, url),
                false,
                statusCode);
    }

    // 业务错误工厂方法
    public static ErrorContext businessError(String message) {
        return new ErrorContext(ErrorType.BUSINESS_ERROR, message, false, null);
    }

    // 网络错误工厂方法
    public static ErrorContext networkError(String message) {
        return new ErrorContext(ErrorType.NETWORK_ERROR, message, true, null);
    }

    public static String translateHttpErrorMessage(int statusCode, String url) {
        return switch (statusCode) {
            case 400 -> String.format("无效请求 (HTTP 400): %s", url);
            case 401 -> String.format("未授权访问 (HTTP 401): %s", url);
            case 403 -> String.format("访问被拒绝 (HTTP 403): %s", url);
            case 404 -> String.format("页面不存在 (HTTP 404): %s", url);
            case 405 -> String.format("请求方法不允许 (HTTP 405): %s", url);
            case 409 -> String.format("请求冲突 (HTTP 409): %s", url);
            case 429 -> String.format("请求太快 (HTTP 429): %s", url);
            case 500 -> String.format("服务器错误 (HTTP 500): %s", url);
            case 502 -> String.format("网关错误 (HTTP 502): %s", url);
            case 503 -> String.format("服务不可用 (HTTP 503): %s", url);
            case 504 -> String.format("网关超时 (HTTP 504): %s", url);
            default -> String.format("HTTP错误 %d: %s", statusCode, url);
        };
    }
}